import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/restaurant_provider.dart';
import '../../models/restaurant.dart';
import '../../core/app_theme.dart';
import '../../core/snackbar_helper.dart'; // 使用新的SnackBar助手

class AddEditRestaurantScreen extends StatefulWidget {
  final Restaurant? restaurant;

  const AddEditRestaurantScreen({
    super.key,
    this.restaurant,
  });

  @override
  State<AddEditRestaurantScreen> createState() => _AddEditRestaurantScreenState();
}

class _AddEditRestaurantScreenState extends State<AddEditRestaurantScreen> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _contactController = TextEditingController();
  final _phoneController = TextEditingController();
  final _addressController = TextEditingController();

  bool _isSaving = false;

  @override
  void initState() {
    super.initState();
    // 如果是编辑模式，用已有数据填充表单
    if (widget.restaurant != null) {
      _nameController.text = widget.restaurant!.name;
      _contactController.text = widget.restaurant!.contact ?? '';
      _phoneController.text = widget.restaurant!.phone ?? '';
      _addressController.text = widget.restaurant!.address ?? '';
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _contactController.dispose();
    _phoneController.dispose();
    _addressController.dispose();
    super.dispose();
  }

  Future<void> _saveRestaurant() async {
    if (!_formKey.currentState!.validate()) return;
    if (_isSaving) return;

    setState(() {
      _isSaving = true;
    });

    try {
      final restaurantProvider = Provider.of<RestaurantProvider>(context, listen: false);
      final restaurant = Restaurant(
        id: widget.restaurant?.id,
        name: _nameController.text.trim(),
        contact: _contactController.text.trim().isEmpty ? null : _contactController.text.trim(),
        phone: _phoneController.text.trim().isEmpty ? null : _phoneController.text.trim(),
        address: _addressController.text.trim().isEmpty ? null : _addressController.text.trim(),
      );

      bool success;
      if (widget.restaurant == null) {
        success = await restaurantProvider.addRestaurant(restaurant);
      } else {
        success = await restaurantProvider.updateRestaurant(restaurant);
      }

      if (success) {
        // 使用SnackBar显示成功提示（底部绿色）
        SnackbarHelper.showSuccess(
          context, 
          widget.restaurant == null ? '饭店添加成功' : '饭店信息已更新'
        );
        
        // 延迟返回让用户看到成功提示
        await Future.delayed(const Duration(milliseconds: 1500));
        Navigator.of(context).pop();
      } else {
        SnackbarHelper.showError(context, '保存失败，请重试');
      }
    } catch (e) {
      // 使用SnackBar显示错误提示（底部红色）
      SnackbarHelper.showError(context, e.toString());
    } finally {
      setState(() {
        _isSaving = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.restaurant == null ? '添加饭店' : '编辑饭店',
          style: AppTheme.titleLarge,
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: ListView(
            children: [
              TextFormField(
                controller: _nameController,
                decoration: const InputDecoration(
                  labelText: '饭店名称*',
                  border: OutlineInputBorder(),
                  labelStyle: AppTheme.bodyMedium,
                ),
                style: AppTheme.bodyLarge,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入饭店名称';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _contactController,
                decoration: const InputDecoration(
                  labelText: '联系人',
                  border: OutlineInputBorder(),
                  labelStyle: AppTheme.bodyMedium,
                ),
                style: AppTheme.bodyLarge,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _phoneController,
                decoration: const InputDecoration(
                  labelText: '电话',
                  border: OutlineInputBorder(),
                  labelStyle: AppTheme.bodyMedium,
                ),
                style: AppTheme.bodyLarge,
                keyboardType: TextInputType.phone,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _addressController,
                decoration: const InputDecoration(
                  labelText: '地址',
                  border: OutlineInputBorder(),
                  labelStyle: AppTheme.bodyMedium,
                ),
                style: AppTheme.bodyLarge,
                maxLines: 3,
              ),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: _isSaving ? null : _saveRestaurant,
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
                child: _isSaving
                    ? const SizedBox(
                        height: 20,
                        width: 20,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Text('保存', style: AppTheme.bodyLarge),
              ),
            ],
          ),
        ),
      ),
    );
  }
}